<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const content = ref('')
const images = ref([])
const video = ref(null)
const isUploading = ref(false)
const currentUser = ref(null)

// 获取当前用户
const getUser = () => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理图片选择
const handleImageSelect = (event) => {
  const files = event.target.files
  if (!files || files.length === 0) return
  
  // 限制最多上传9张图片
  if (images.value.length + files.length > 9) {
    alert('最多只能上传9张图片')
    return
  }
  
  // 模拟上传过程
  isUploading.value = true
  
  setTimeout(() => {
    Array.from(files).forEach(file => {
      // 在实际应用中，这里应该上传图片到服务器
      // 这里使用placeholder图片作为示例
      const reader = new FileReader()
      reader.onload = (e) => {
        images.value.push(e.target.result)
      }
      reader.readAsDataURL(file)
    })
    
    isUploading.value = false
    // 清空文件输入
    event.target.value = ''
  }, 500)
}

// 处理视频选择
const handleVideoSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查视频大小（限制100MB）
  if (file.size > 100 * 1024 * 1024) {
    alert('视频大小不能超过100MB')
    return
  }
  
  // 模拟上传过程
  isUploading.value = true
  
  setTimeout(() => {
    // 在实际应用中，这里应该上传视频到服务器
    // 这里使用placeholder视频作为示例
    const reader = new FileReader()
    reader.onload = (e) => {
      video.value = e.target.result
    }
    reader.readAsDataURL(file)
    
    isUploading.value = false
    // 清空文件输入
    event.target.value = ''
  }, 1000)
}

// 删除图片
const removeImage = (index) => {
  images.value.splice(index, 1)
}

// 移除视频
const removeVideo = () => {
  video.value = null
}

// 发布帖子
const publishPost = () => {
  if (!content.value.trim() && images.value.length === 0 && !video.value) {
    alert('请输入内容或上传媒体文件')
    return
  }
  
  // 创建新帖子
  const newPost = {
    id: Date.now().toString(),
    author: currentUser.value.username,
    content: content.value.trim(),
    images: [...images.value],
    video: video.value || null,
    createdAt: new Date().toISOString(),
    likes: [],
    comments: []
  }
  
  // 保存到localStorage
  const savedPosts = localStorage.getItem('socialPosts')
  const allPosts = savedPosts ? JSON.parse(savedPosts) : []
  
  // 添加到开头，实现最新的帖子在前面
  allPosts.unshift(newPost)
  localStorage.setItem('socialPosts', JSON.stringify(allPosts))
  
  // 跳转到社区首页
  router.push('/social')
}

onMounted(() => {
  currentUser.value = getUser()
  
  // 如果用户未登录，重定向到登录页
  if (!currentUser.value) {
    router.push('/login')
  }
})
</script>

<template>
  <div class="create-post-container">
    <!-- 头部导航 -->
    <header class="create-header">
      <button class="back-btn" @click="goBack">取消</button>
      <h1>发布</h1>
      <button 
        class="publish-btn" 
        :disabled="isUploading || (!content.trim() && images.length === 0 && !video)"
        @click="publishPost"
      >
        发布
      </button>
    </header>

    <!-- 发布表单 -->
    <div class="create-content">
      <!-- 用户信息 -->
      <div class="user-info">
        <div class="avatar">{{ currentUser?.username?.charAt(0).toUpperCase() || '?' }}</div>
        <div class="username">{{ currentUser?.username || '' }}</div>
      </div>

      <!-- 内容输入 -->
      <div class="content-input-area">
        <textarea
          v-model="content"
          placeholder="分享你的想法..."
          class="content-textarea"
          rows="5"
          maxlength="2000"
        ></textarea>
        <div class="char-count">{{ content.length }}/2000</div>
      </div>

      <!-- 媒体预览 -->
      <div v-if="images.length > 0 || video" class="media-preview">
        <!-- 图片预览 -->
        <div v-if="images.length > 0" class="image-preview-grid">
          <div v-for="(image, index) in images" :key="index" class="preview-image-wrapper">
            <img :src="image" :alt="`预览图片 ${index + 1}`" class="preview-image">
            <button 
              class="remove-image-btn" 
              @click="removeImage(index)"
              title="删除图片"
            >
              ×
            </button>
          </div>
        </div>

        <!-- 视频预览 -->
        <div v-if="video" class="video-preview-wrapper">
          <video :src="video" controls class="preview-video"></video>
          <button 
            class="remove-video-btn" 
            @click="removeVideo"
            title="删除视频"
          >
            ×
          </button>
        </div>
      </div>

      <!-- 上传选项 -->
      <div class="upload-options">
        <label class="upload-btn image-upload">
          <input 
            type="file" 
            accept="image/*" 
            multiple 
            @change="handleImageSelect"
            style="display: none;"
          >
          <span class="upload-icon">📷</span>
          <span class="upload-text">上传图片</span>
        </label>
        
        <label class="upload-btn video-upload">
          <input 
            type="file" 
            accept="video/*" 
            @change="handleVideoSelect"
            style="display: none;"
          >
          <span class="upload-icon">🎬</span>
          <span class="upload-text">上传视频</span>
        </label>
      </div>

      <!-- 上传状态 -->
      <div v-if="isUploading" class="uploading-indicator">
        <div class="loading-spinner"></div>
        <span>上传中...</span>
      </div>

      <!-- 提示信息 -->
      <div class="posting-tips">
        <p>📌 小贴士：</p>
        <ul>
          <li>文字最多2000字</li>
          <li>最多可上传9张图片</li>
          <li>视频大小限制100MB</li>
          <li>请遵守社区规范，文明发言</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped>
.create-post-container {
  max-width: 100%;
  margin: 0 auto;
  background-color: white;
  min-height: 100vh;
}

.create-header {
  position: sticky;
  top: 0;
  background-color: white;
  padding: 16px 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  background: none;
  border: none;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  padding: 4px 12px;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #f0f0f0;
}

.create-header h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.publish-btn {
  padding: 8px 16px;
  background-color: #ff0000;
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.publish-btn:hover:not(:disabled) {
  background-color: #e60000;
}

.publish-btn:disabled {
  background-color: #ff9999;
  cursor: not-allowed;
}

.create-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 16px 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #ff6b6b;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.content-input-area {
  position: relative;
  margin-bottom: 20px;
}

.content-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid transparent;
  border-radius: 8px;
  font-size: 16px;
  line-height: 1.5;
  resize: none;
  outline: none;
  transition: border-color 0.2s;
  background-color: #f9f9f9;
  min-height: 150px;
}

.content-textarea:focus {
  border-color: #ff0000;
  background-color: white;
}

.char-count {
  position: absolute;
  bottom: 8px;
  right: 12px;
  font-size: 12px;
  color: #999;
}

.media-preview {
  margin-bottom: 20px;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 8px;
}

.preview-image-wrapper {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  aspect-ratio: 1/1;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn, .remove-video-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-preview-wrapper {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
}

.preview-video {
  width: 100%;
  max-height: 400px;
}

.upload-options {
  display: flex;
  gap: 24px;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #666;
  padding: 8px 16px;
  border-radius: 20px;
  transition: background-color 0.2s;
}

.upload-btn:hover {
  background-color: #f0f0f0;
}

.upload-icon {
  font-size: 20px;
}

.upload-text {
  font-size: 14px;
}

.uploading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  color: #666;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #ff0000;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.posting-tips {
  margin-top: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.posting-tips p {
  margin: 0 0 8px 0;
  font-weight: 500;
  color: #333;
}

.posting-tips ul {
  margin: 0;
  padding-left: 20px;
}

.posting-tips li {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

@media (max-width: 768px) {
  .create-header {
    padding: 12px 16px;
  }
  
  .create-content {
    padding: 16px;
  }
  
  .image-preview-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>